package com.vichat.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class LocationUtil {

    private static transient Log log = LogFactory.getLog(LocationUtil.class);
    private static double jl_jd = 102834.74258026089786013677476285;
    private static double jl_wd = 111712.69150641055729984301412873;
    private static String url = "http://restapi.amap.com/v3/assistant/coordinate/convert?coordsys=gps&key=685d56ae1d9429270a0e348f0d9ea0f2&locations=";
    private static String urlAddr = "http://restapi.amap.com/v3/geocode/regeo?output=json&key=685d56ae1d9429270a0e348f0d9ea0f2&radius=1000&extensions=all&location=";
    private static double EARTH_RADIUS = 6378.137;

    public static String[] getMapLocationSingle(String params) throws Exception {
        return getMapLocation(params)[0].split(",");
    }
    
    public static String getMapAddress(String params) throws Exception {
        String address = "";
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);
        JSONObject jsonObject = new JSONObject();
        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpGet httpGet = new HttpGet(urlAddr + params);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) { // SC_OK = 200
                String response = EntityUtils.toString(httpResponse.getEntity());
                JSONObject obj= JSON.parseObject(response);
                jsonObject = JSON.parseObject(obj.get("regeocode").toString());
                address = jsonObject.get("formatted_address").toString();
            }
        } catch (Exception e) {
            log.error("获取地址信息失败", e);
        }
        return address;
    }

    public static String[] getMapLocation(String params) throws Exception {
        JSONObject jsonObject = new JSONObject();

        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 3000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpClient = new DefaultHttpClient(httpParameters);
        HttpGet httpGet = new HttpGet(url + params);
        try {
            HttpResponse httpResponse = httpClient.execute(httpGet);
            int statusCode = httpResponse.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) { // SC_OK = 200
                String response = EntityUtils.toString(httpResponse.getEntity());
                jsonObject = JSON.parseObject(response);
                String[] split = jsonObject.get("locations").toString().split(";");
                return split;
            }
        } catch (Exception e) {
            log.error("解析地图坐标失败", e);
        }
        return new String[] { "0,0" };
    }

    public static List<String> createTable(Calendar instance) throws Exception {
        List<String> tables = new ArrayList<>();
        int lastDay = instance.getActualMaximum(Calendar.DAY_OF_MONTH);
        for (int i = 1; i <= lastDay; i++) {
            String name = DateUtil.getYearMonth(new Timestamp(instance.getTimeInMillis()))
                    + ((i < 10) ? "0" + i : i);
            StringBuilder sql = new StringBuilder();
            sql.append("CREATE TABLE `location_data_").append(name).append("` (");
            sql.append("`loc_id` bigint(20) NOT NULL AUTO_INCREMENT,");
            sql.append("`uid` char(12) DEFAULT NULL COMMENT '人员ID',");
            sql.append("`dev_id` char(20) NOT NULL COMMENT '设备ID',");
            sql.append("`longitude` decimal(14,8) NOT NULL COMMENT '经度',");
            sql.append("`latitude` decimal(14,8) NOT NULL COMMENT '纬度',");
            sql.append("`map_longi` decimal(12,8) DEFAULT NULL,");
            sql.append("`map_lati` decimal(12,8) DEFAULT NULL,");
            sql.append("`height` decimal(10,2) DEFAULT '0.00' COMMENT '高度',");
            sql.append("`temperature` decimal(10,2) DEFAULT '0.00' COMMENT '温度',");
            sql.append("`speed` decimal(10,2) DEFAULT '0.00' COMMENT '速度或电量',");
            sql.append("`direction` decimal(10,2) DEFAULT '0.00',");
            sql.append("`battery` decimal(8,2) DEFAULT '0.00' COMMENT '电量',");
            sql.append("`rfid_mode` tinyint(4) DEFAULT '-1' COMMENT '0为GPS，1为基站，2为RFID',");
            sql.append("`voltage_state` decimal(8,2) DEFAULT '0.00' COMMENT '电压状态',");
            sql.append("`check_state` decimal(8,2) DEFAULT '-1.00' COMMENT '巡检状态',");
            sql.append("`loc_state` char(2) DEFAULT '-1',");
            sql.append("`event_desc` varchar(255) DEFAULT NULL,");
            sql.append("`gather_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,");
            sql.append("`is_show` tinyint(4) NOT NULL DEFAULT '0',");
            sql.append("`ext_flag1` varchar(100) DEFAULT '',");
            sql.append("`ext_flag2` varchar(100) DEFAULT '',");
            sql.append("`img_id` varchar(100) DEFAULT '0',");
            sql.append("PRIMARY KEY (`loc_id`),");
            sql.append("KEY `idx_location_uid` (`uid`) USING BTREE,");
            sql.append("KEY `idx_location_time` (`gather_time`) USING BTREE");
            sql.append(") ENGINE=InnoDB DEFAULT CHARSET=utf8;");
            tables.add(sql.toString());
        }
        return tables;
    }

    public static int getDistance(double lat1,double lont1,double lat2,double lont2){
        double b = Math.abs((lont1 - lont2) * jl_jd);
        double a = Math.abs((lat1 - lat2) * jl_wd);
        double dinst = Math.sqrt((a * a + b * b));
        return (int)dinst;
    }

    private static double rad(double d) {
        return d * Math.PI / 180.0;
    }

    /**
     * 通过经纬度获取距离(单位：米)
     * @param lat1
     * @param lng1
     * @param lat2
     * @param lng2
     * @return
     */
    public static double getDoubleDistance(double lat1, double lng1, double lat2,
                                     double lng2) {
        double radLat1 = rad(lat1);
        double radLat2 = rad(lat2);
        double a = radLat1 - radLat2;
        double b = rad(lng1) - rad(lng2);
        double s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
                + Math.cos(radLat1) * Math.cos(radLat2)
                * Math.pow(Math.sin(b / 2), 2)));
        s = s * EARTH_RADIUS;
        s = Math.round(s * 10000d) / 10000d;
        s = s*1000;
        return s;
    }


    public static String getLocationDataTableName(Date date) {
        String name = DateUtil.getYearMonthDay(date);
        return "gpsdb.location_data_" + name;
    }
    public static String getLocationDataTableName(String date) {
        return "gpsdb.location_data_" + date;
    }

    public static String getLocationDevice(Date date) {
        String name = DateUtil.getYearMonthDay(date);
        return "gpsdb.location_device_" + name;
    }


    public static void main(String[] args) throws Exception {
        Double lat1 = Double.parseDouble("31.23946181");
        Double long1 = Double.parseDouble("121.47852295");

        Double lat2 = Double.parseDouble("31.23976183");
        Double long2 = Double.parseDouble("121.47852295");

        System.out.print(getDistance(lat1,long1,lat2,long2));
    }

}
